package org.base.common.fs;

import lombok.Data;
import org.apache.commons.io.IOUtils;
import org.base.common.pojo.FileInfo;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.time.LocalDate;

/**
 * 本地文件系统
 */
@Data
public class LocalFileSystem implements FileSystem {

    /**
     * 文件存储路径
     */
    private String storePath;

    /**
     * 文件访问上下文
     */
    private String contextPath;

    public LocalFileSystem(String storePath, String contextPath) {
        this.storePath = storePath;
        this.contextPath = contextPath;
        if (!this.contextPath.endsWith("/")) {
            this.contextPath += "/";
        }
    }

    @Override
    public FileInfo upload(MultipartFile file) throws IOException {
        FileInfo fileInfo = new FileInfo();
        long size = file.getSize();
        String originalFilename = file.getOriginalFilename();
        String ext = getFileExt(originalFilename);

        String parent = getParentDir();
        String storeName = getStoreName(parent) + ext;

        File parentDir = new File(storePath, parent);
        if (!parentDir.exists()) {
            parentDir.mkdirs();
        }

        try (InputStream inputStream = file.getInputStream();
             FileOutputStream outputStream = new FileOutputStream(new File(parentDir, storeName))
        ) {
            IOUtils.copy(inputStream, outputStream);
        }

        fileInfo.setOriginalFilename(originalFilename);
        fileInfo.setSize(size);
        fileInfo.setUrl(contextPath + parent + storeName);
        return fileInfo;
    }

    private String getFileExt(String originalFilename) {
        return originalFilename.substring(originalFilename.lastIndexOf("."));
    }

    private String getStoreName(String dir) {
        return Thread.currentThread().getId() + "" + System.currentTimeMillis();
    }

    private String getParentDir() {
        LocalDate now = LocalDate.now();
        return now.getYear() + "/" + now.getMonthValue() + "/";
    }

    @Override
    public InputStream getFileInputStream(String fileName) throws FileNotFoundException {
        final String[] split = fileName.split("-");
        return getInputStream(split[0] + "/" + split[1] + "/" + fileName);
    }

    private InputStream getInputStream(String fileName) throws FileNotFoundException {
        return new FileInputStream(new File(storePath, fileName));
    }

    @Override
    public InputStream getFileInputStream(String dir, String fileName) throws FileNotFoundException {
        return getInputStream(dir + "/" + fileName);
    }
}
